/**
 * $version:  0.1 
 * $Date: 2012-05-12 
 *
 * Copyright (C) 2010-2012 Jawa Software. All rights reserved.
 *
 */
package org.jawa.database;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.jawa.util.JawaGlobals;
import org.jawa.util.Log;
import org.logicalcobwebs.proxool.ProxoolFacade;

/**
 * 提供Embedded DB的数据库连接池.
 */
public class EmbeddedConnectionProvider implements ConnectionProvider {

	private Properties settings;
	private String serverURL;
	private String driver = "org.hsqldb.jdbcDriver";
	private String proxoolURL;

	public EmbeddedConnectionProvider() {
		//System.setProperty("org.apache.commons.logging.LogFactory", "org.jawa.util.CommonsLogFactory");
	}

	public boolean isPooled() {
		return true;
	}

	public Connection getConnection() throws SQLException {
		try {
			Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
			return DriverManager.getConnection(proxoolURL, settings);
		} catch (ClassNotFoundException e) {
			throw new SQLException("EmbeddedConnectionProvider: 找不到驱动程序: " + e);
		}
	}

	public void start() {
		File databaseDir = new File(JawaGlobals.getHomeDirectory(), File.separator + "embedded-db");
		if (!databaseDir.exists()) {
			databaseDir.mkdirs();
		}

		try {
			serverURL = "jdbc:hsqldb:" + databaseDir.getCanonicalPath() + File.separator + "jawa";
		} catch (IOException ioe) {
			Log.error("EmbeddedConnectionProvider: 连接池启动错误: ", ioe);
		}
		proxoolURL = "proxool.jawa:" + driver + ":" + serverURL;
		settings = new Properties();
		settings.setProperty("database.defaultProvider.maxConnections", "25");
		settings.setProperty("database.defaultProvider.minConnections", "3");
		settings.setProperty("database.defaultProvider.connectionTimeout", "1");
		settings.setProperty("database.defaultProvider.username", "sa");
		settings.setProperty("database.defaultProvider.password", "");
	}

	public void restart() {
		destroy();
		start();
	}

	public void destroy() {
		Connection con = null;
		try {
			con = getConnection();
			Statement stmt = con.createStatement();
			stmt.execute("SHUTDOWN");
			stmt.close();
		} catch (SQLException sqle) {
			Log.error(sqle);
		} finally {
			try {
				if (con != null) {
					con.close();
				}
			} catch (Exception e) {
				Log.error(e);
			}
		}
		settings = null;
		ProxoolFacade.shutdown(0);
	}

	public void finalize() throws Throwable {
		super.finalize();
		destroy();
	}
}